package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC154 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public int findMin(int[] arr) {
            if (arr.length <= 1) return arr[0];
            int left = 0, right = arr.length - 1, mid;
            while (right - left >= 2) {
                mid = left + (right - left) / 2;
                if (arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1])
                    return arr[mid + 1] <= arr[mid - 1] ? arr[mid + 1] : arr[mid - 1];
                if (arr[mid] >= arr[left] && arr[mid] > arr[right]) left = mid;
                else if (arr[mid] < arr[left] && arr[mid] < arr[right]) right = mid;
                else if (arr[mid] <= arr[left] && arr[mid] >= arr[right]) ++left;
                else if (arr[mid] >= arr[left] && arr[mid] <= arr[right]) --right;
                else {
                    System.out.println("unknown : left:" + left + " right:" + right);
                }
            }

            return arr[left] <= arr[right] ? arr[left] : arr[right];
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[3,1,3]");
        System.out.println(solution.findMin(arr));
    }

    public static void main(String[] args) throws Exception {
        LC154 an = new LC154();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
